#include <bits/stdc++.h>

#define in read()
#define fi first
#define se second
#define pii pair<int,int>
#define pb push_back
#define vec vector<int>
#define y1 y_____hahahaha_____1

using namespace std;

typedef long long ll;
typedef double db;
typedef unsigned long long ull;
typedef long double ldb;

int read(){int x = 0,sgn = 1;char ch = getchar();for(;!isdigit(ch);ch = getchar()) if(ch == '-') sgn = -1;for(;isdigit(ch);ch = getchar()) x = (x << 1) + (x << 3) + (ch ^ 48); return x * sgn;}

const int M = 210;
const int N = 1010;

int f[2][M][M],p[N],d[M][M],n,m;

void upd(int &x,int y){x = min(x,y);}

int main(){
#ifndef ONLINE_JUDGE
	freopen("1.in","r",stdin);
#endif
	m = in; for(int i = 1;i <= m;i++) for(int j = 1;j <= m;j++) d[i][j] = in;
	p[++n] = 3; int o = 0; memset(f[o],0x3f,sizeof f[o]); f[o][1][2] = 0;
	while(scanf("%d",&p[n + 1]) == 1) n++;
	for(int i = 1;i < n;i++,o ^= 1){
		memset(f[o ^ 1],0x3f,sizeof f[o ^ 1]);
		for(int j = 1;j <= m;j++)
			for(int k = 1;k <= m;k++)
				if(f[o][j][k] < 1e9){
					upd(f[o ^ 1][j][k],f[o][j][k] + d[p[i]][p[i + 1]]);
					upd(f[o ^ 1][p[i]][k],f[o][j][k] + d[j][p[i + 1]]);
					upd(f[o ^ 1][j][p[i]],f[o][j][k] + d[k][p[i + 1]]);
				}
	} int ans = 1e9;
	for(int i = 1;i <= m;i++) for(int j = 1;j <= m;j++) ans = min(ans,f[o][i][j]);
	printf("%d\n",ans);
	return 0;
}
